package com.czzapp.xiaoyumemo.provider;

import java.io.File;
import java.sql.Date;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class MemoProvider extends ContentProvider {
	//定义MIME类型
    public static final String AUTHORITY = "com.czzapp.xiaoyumemo";
    public static final Uri MEMO_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/memos");
    public static final Uri AUDIO_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/audios");
//    public static final Uri COMING_MEMO_CONTENT_URI = Uri.withAppendedPath(MEMO_CONTENT_URI, "coming");
//    public static final Uri MISSED_MEMO_CONTENT_URI = Uri.withAppendedPath(MEMO_CONTENT_URI, "missed");
//    public static final Uri GONE_MEMO_CONTENT_URI = Uri.withAppendedPath(MEMO_CONTENT_URI, "gone");
    
    //只需要定义是属于dir还是item就可以了
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.czzapp.memos";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.czzapp.memo";
    
    
    //定义表格
    public  static final String MEMO_TABLE_ID = BaseColumns._ID;
    public static final String TITLE = "title";
    public static final String CONTENT = "content";
    public static final String AUDIO_PATH = "audio_path";
    public static final String INIT_DATE = "init_date";
    public static final String DELAY_DATE = "delay_date";
    public static final String STATE = "state";
    public static final int MEMO_STATE_COMING = 0;
    public static final int MEMO_STATE_MISSED = 1;
    public static final int MEMO_STATE_GONE = 2;
    private static final String DEFAULT_SORT_ORDER = INIT_DATE + " asc";
    
    public static final String AUDIO_TABLE_ID = BaseColumns._ID;
    public static final String PATH = "path";
    public static final String AUDIO_REFERENCE = "reference";
    
    private static final String DATABASE_NAME = "xiaoyumemo.db";
    private static final int DATABASE_VERSION = 2;
    private static final String MEMOS_TABLE_NAME = "memos";
    private static final String AUDIOS_TABLE_NAME = "audios";
    
    //返回的支持的URI的类型
    private static final int MEMO_ID = 0;
    private static final int MEMOS = 1;
    private static final int AUDIO_ID = 2;
    private static final int AUDIOS = 3;
    
    private static final UriMatcher sUriMatcher;
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, "memos", MEMOS);
        sUriMatcher.addURI(AUTHORITY, "memos/#", MEMO_ID);
        sUriMatcher.addURI(AUTHORITY, "audios", AUDIOS);
        sUriMatcher.addURI(AUTHORITY, "audios/#", AUDIO_ID);
    }
    
    private DatabaseHelper mOpenHelper;
    
    private static class DatabaseHelper {
    	String mDatabasePath = null;
    	SQLiteDatabase mWritableDatabase = null;
    	SQLiteDatabase mReadableDatabase = null;
    	
    	DatabaseHelper(String databasePath) {
    		mDatabasePath = databasePath;
    		File file  = new File(databasePath);
    		if(!file.exists()) {
    			createDatabase();
    		}
		}
    	
    	SQLiteDatabase getReadableDatabase() {
    		if(mReadableDatabase == null) {
    			try {
	    			mReadableDatabase = SQLiteDatabase.openDatabase(mDatabasePath, null, SQLiteDatabase.OPEN_READONLY);
    			}
    			catch (SQLiteException ex) {
    			}
    		}
    		return mReadableDatabase;
    	}
    	
    	SQLiteDatabase getWritableDatabase() {
    		if(mWritableDatabase == null) {
    			try {
	    			mWritableDatabase = SQLiteDatabase.openDatabase(mDatabasePath, null, SQLiteDatabase.OPEN_READWRITE);
    			}
    			catch (SQLiteException ex) {
    			}
    		}
    		return mWritableDatabase;
    	}
    	
    	private void createDatabase() {
	    	mWritableDatabase = SQLiteDatabase.openOrCreateDatabase(mDatabasePath, null);
            mWritableDatabase.execSQL("CREATE TABLE " + MEMOS_TABLE_NAME + " ("
                    + MEMO_TABLE_ID + " INTEGER PRIMARY KEY,"
                    + TITLE + " TEXT,"
                    + CONTENT + " TEXT,"
                    + INIT_DATE + " INTEGER,"
                    + DELAY_DATE + " INTEGER,"
                    + AUDIO_PATH + " TEXT,"
                    + STATE + " INTEGER"
                    + ");");
            mWritableDatabase.execSQL("CREATE TABLE " + AUDIOS_TABLE_NAME + " ("
            		+ AUDIO_TABLE_ID + " INTEGER PRIMARY KEY,"
            		+ PATH + " TEXT,"
            		+ AUDIO_REFERENCE + " INTEGER"
                    + ");");
    	}
    }
    
    private static class NotSdcardDatabaseHelper extends SQLiteOpenHelper {

        NotSdcardDatabaseHelper (Context context, String databasePath) {
            super(context, databasePath, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + MEMOS_TABLE_NAME + " ("
                    + MEMO_TABLE_ID + " INTEGER PRIMARY KEY,"
                    + TITLE + " TEXT,"
                    + CONTENT + " TEXT,"
                    + INIT_DATE + " INTEGER,"
                    + DELAY_DATE + " INTEGER,"
                    + AUDIO_PATH + " TEXT,"
                    + STATE + " INTEGER"
                    + ");");
            db.execSQL("CREATE TABLE " + AUDIOS_TABLE_NAME + " ("
            		+ AUDIO_TABLE_ID + " INTEGER PRIMARY KEY,"
            		+ PATH + " TEXT,"
            		+ AUDIO_REFERENCE + " INTEGER"
                    + ");");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }
   
	@Override
	public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case MEMOS:
        	return CONTENT_TYPE;
        case MEMO_ID:
        	return CONTENT_ITEM_TYPE;
        case AUDIOS:
        	return CONTENT_TYPE;
        case AUDIO_ID:
        	return CONTENT_ITEM_TYPE;
    	default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}
	
	@Override
	public boolean onCreate() {
		//nothing to do
		return true;
	}

	private boolean openDatabase() {
		boolean isSdcardMounted = Environment.getExternalStorageState().compareTo(Environment.MEDIA_MOUNTED) == 0;
		if(!isSdcardMounted) {
			return false;
		}
		String databasePath = Environment.getExternalStorageDirectory() + File.separator + DATABASE_NAME;
		try {
	        mOpenHelper = new DatabaseHelper(databasePath);
	        return true;
		}
		catch (SQLiteException ex) {
	        return false;
		}
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
		if(mOpenHelper == null) {
			if(!openDatabase()) {
				return null;
			}
		}
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(MEMOS_TABLE_NAME);
        switch (sUriMatcher.match(uri)) {
        case MEMOS:
            break;
        case MEMO_ID:
            qb.appendWhere(MEMO_TABLE_ID + "=" + uri.getPathSegments().get(1));
            break;
        case AUDIOS:
        	break;
        case AUDIO_ID:
            qb.appendWhere(AUDIO_TABLE_ID + "=" + uri.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }
        SQLiteDatabase db = null;
        //可能没有数据库，需要创建
        try {
	        db = mOpenHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
        }
        catch (SQLException e) {
        	//这一句是在使用SQLiteOpenHelper的时候才用到，因为它的创建不是在构造函数时创建
//        	db = mOpenHelper.getWritableDatabase();
        	return null;
        }
	}
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		if(mOpenHelper == null) {
			return -1;
		}
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case MEMOS:
            count = db.delete(MEMOS_TABLE_NAME, where, whereArgs);
            break;
        case MEMO_ID:
            String memoId = uri.getPathSegments().get(1);
            count = db.delete(MEMOS_TABLE_NAME, MEMO_TABLE_ID + "=" + memoId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        case AUDIOS:
        	count = db.delete(AUDIOS_TABLE_NAME, where, whereArgs);
        	break;
        case AUDIO_ID:
            String audioId = uri.getPathSegments().get(1);
            count = db.delete(AUDIOS_TABLE_NAME, AUDIO_TABLE_ID + "=" + audioId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		if(mOpenHelper == null) {
			return null;
		}
		boolean isSupportedUri = false;
		Uri contentUri = null;
		String tableName = null;
        if (sUriMatcher.match(uri) == MEMOS) {
        	isSupportedUri = true;
        	contentUri = MEMO_CONTENT_URI;
        	tableName = MEMOS_TABLE_NAME;
        }
        else if(sUriMatcher.match(uri) == AUDIOS) {
        	isSupportedUri = true;
        	contentUri = AUDIO_CONTENT_URI;
        	tableName = AUDIOS_TABLE_NAME;
        }
		if (isSupportedUri) {
			ContentValues values = new ContentValues(initialValues);
			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			long rowId = db.insert(tableName, null, values);
			if (rowId > 0) {
				Uri noteUri = ContentUris.withAppendedId(contentUri,
						rowId);
				getContext().getContentResolver().notifyChange(noteUri, null);
				return noteUri;
			}
			throw new SQLException("Failed to insert row into " + uri);
		}
		else {
	       throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		if(mOpenHelper == null) {
			return -1;
		}
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case MEMOS:
            count = db.update(MEMOS_TABLE_NAME, values, where, whereArgs);
            break;
        case MEMO_ID:
            String memoId = uri.getPathSegments().get(1);
            count = db.update(MEMOS_TABLE_NAME, values, MEMO_TABLE_ID + "=" + memoId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        case AUDIOS:
            count = db.update(AUDIOS_TABLE_NAME, values, where, whereArgs);
            break;
        case AUDIO_ID:
            String audioId = uri.getPathSegments().get(1);
            count = db.update(AUDIOS_TABLE_NAME, values, AUDIO_TABLE_ID + "=" + audioId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;
        default:
        	throw new IllegalArgumentException("URI not supporting update " + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
}
